/*
链队列实现
初始化 initqueue();
入队   add()
出队   push
*/
#include <stdio.h>
#include <stdlib.h>
// 队列的节点结构
typedef struct QNode
{
    int data;
    struct QNode *next;
} QNode, *QueuePtr;

// 队列的链结构
typedef struct LinkQueue
{
    // 头尾指针
    QueuePtr front, rear;
} linkqueue;

void visit(int data)
{
    printf("%d ", data);
}

void printqueue(linkqueue *queue)
{
    QueuePtr p;
    p = queue->front->next;
    while (p != NULL)
    {
        visit(p->data);
        p = p->next;
    }
    putchar('\n');
}








void initqueue(linkqueue *queue)
{
    printf("init queue -> %p\n", queue);
    QueuePtr tmp = (QueuePtr) malloc(sizeof(struct QNode));
    queue->front = tmp;
    queue->rear = tmp;

    queue->front->next = NULL;
    // queue->front = NULL;
    // queue->rear  = NULL;
}

void addItem(linkqueue *queue, int data)
{
    QueuePtr tmp; // 新建的节点
    tmp = (QueuePtr) malloc(sizeof(struct QNode));
    tmp->data = data;
    tmp->next = NULL;
    
    queue->rear->next = tmp;
    queue->rear  = tmp;
}

void delItem(linkqueue *queue, int *data)
{
    // 当队列不为空时出队元素
    // int flag = isEmpty(queue);
    /* if (queue->front->next == NULL)
    {
        printf("queue is empty now, operator error!");
        system("pause");
        exit(-1);
    } */
    // 上面的和上面的一样
    if (queue->front == queue->rear)
    {
        printf("queue is empty now, operator error!");
        system("pause");
        exit(-1);
    }
    QueuePtr p = queue->front->next;
    *data = p->data;
    queue->front->next = p->next;
    if (queue->rear == p) // 若队头是队尾，则删除后将rear指向头结点
    {
        queue->rear = queue->front;
    }
    printf("in delItem data is -> %d\n", *data);
    free(p);
}

int isEmpty(linkqueue *queue)
{
    if (queue->front->next == NULL)
    {
        return 1; // is empty
    }
    return 0; // is have elem
}